function generateUUID() {
  let d = new Date().getTime(); //Timestamp
  let d2 = (performance && performance.now && performance.now() * 1000) || 0; //Time in microseconds since page-load or 0 if unsupported
  return "uxxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    let r = Math.random() * 16; //random number between 0 and 16
    if (d > 0) {
      //Use timestamp until depleted
      r = (d + r) % 16 | 0;
      d = Math.floor(d / 16);
    } else {
      //Use microseconds since page-load if supported
      r = (d2 + r) % 16 | 0;
      d2 = Math.floor(d2 / 16);
    }
    return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
  });
}

module.exports = function (source) {
  const { module } = this.getOptions();
  const extractClassNameReg = /(?<=\.)(.*?)(?={)/g;
  const classNameMap = source
    .match(extractClassNameReg)
    .reduce((reducedMap, currentClassName) => {
      return {
        ...reducedMap,
        [currentClassName.trim()]: currentClassName.trim(),
      };
    }, {});

  if (module) {
    // handle scope
    Object.keys(classNameMap).forEach((classNameKey) => {
      const id = generateUUID();
      const newClassName = `${id}-${classNameMap[classNameKey]}`;
      classNameMap[classNameKey] = newClassName;
    });
  }

  return `/**__CSS_SOURCE__${source.replace(extractClassNameReg, (_, key) => {
    return classNameMap[key] || key;
  })}*//**__CSS_classKeyMap__${JSON.stringify(classNameMap)}*/`;
};
